import dayjs from 'dayjs'

/**
 * 获取当前日期 YYYY-DD-MM
 * @returns
 */
export const getNowDate = () => {
	const now = new Date()
	const year = now.getFullYear()
	const month = (now.getMonth() + 1).toString().padStart(2, '0') // 0~11
	const day = now.getDate().toString().padStart(2, '0')
	return `${year}-${month}-${day}`
}

/**
 * 获取半小时时间
 * @author 张三
 * @returns [startTime, endTime]
 */
export const getHalfHourTime = () => {
	const currentTime = dayjs()
	const halfHourAgo = currentTime.subtract(0.5, 'hour') // 获取半小时前的时间
	const endTime = currentTime.format('YYYY-MM-DD HH:mm:ss')
	const startTime = halfHourAgo.format('YYYY-MM-DD HH:mm:ss')
	return [startTime, endTime]
}

/**
 * 格式化日期
 * @param dateString 日期字符串
 * @returns 格式化后的日期字符串
 */
export function formatDate(dateString: string) {
	const date = new Date(dateString)
	const year = date.getFullYear()
	const month = (date.getMonth() + 1).toString().padStart(2, '0') // 月份是从0开始的
	const day = date.getDate().toString().padStart(2, '0')
	const hours = date.getHours().toString().padStart(2, '0')
	const minutes = date.getMinutes().toString().padStart(2, '0')
	const seconds = date.getSeconds().toString().padStart(2, '0')
	return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}

/**
 * 格式化日期
 * toLocaleDateString(new Date()) --- 2024/1/1
 * toLocaleTimeString 00:00:00
 * toLocaleString(new Date()) --- 2024/1/1 00:00:00
 * @param {Date} date 日期
 * @param {"yyyy-MM-dd" | "HH:mm:ss" | string} rule 规则
 * @returns

 */
export const toLocalDate = (date, rule) => {
	const curDate = date || new Date()
	switch (rule) {
		case 'yyyy-MM-dd': // 日期
			return curDate.toLocaleDateString().replace('/', '-')
		case 'HH:mm:ss': // 时间
			return curDate.toLocaleTimeString().replace('/', '-')
		default: // 日期和时间
			return curDate.toLocaleString().replace('/', '-')
	}
}

/**
 * 格式化日期
 * @param {Date | string} date
 * @param {string} rule
 * @returns
 */

export const formatDates = (date: Date | string, rule: string) => {
	let curDate = new Date()
	if (date instanceof Date) curDate = date
	else if (date) curDate = new Date(date)
	let fmt = rule || 'yyyy-MM-dd HH:mm:ss'
	fmt = fmt.replace(/(y+)/, curDate.getFullYear().toString())
	const O = {
		'M+': curDate.getMonth() + 1,
		'd+': curDate.getDate(),
		'H+': curDate.getHours(),
		'm+': curDate.getMinutes(),
		's+': curDate.getSeconds()
	}
	for (const k in O) {
		fmt = fmt.replace(new RegExp(`(${k})`), O[k] > 9 ? O[k].toString() : '0' + O[k].toString())
	}
	return fmt
}
